package com.example.demo.grpc.service;

import com.example.demo.Request;
import com.example.demo.Response;
import com.example.demo.grpc.utils.MsgBuilder;
import com.example.demo.grpc.utils.MsgParse;
import com.example.demo.hello.Bb;
import com.example.demo.hello.HelloRequest;
import com.example.demo.hello.HelloResponse;
import com.google.protobuf.InvalidProtocolBufferException;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.service.GrpcService;

/**
 * @author ls
 * @description
 * @date 2025/6/5 17:33
 */
@GrpcService
@Slf4j
public class HelloServiceGrpc extends com.example.demo.HelloServiceGrpc.HelloServiceImplBase {
    @Override
    public void sayHello(Request request, StreamObserver<Response> responseObserver) {
        try {
            HelloRequest data = MsgParse.parseReqBody(request);
            log.info("receive request: {}", data.getName());
            HelloResponse helloResponse = HelloResponse.newBuilder().setMessage(data.getName())
                    .setBb(Bb.newBuilder().setB1(data.getAa().getA1()).setB2(data.getAa().getA2()).build())
                    .build();
            responseObserver.onNext(MsgBuilder.success(helloResponse));
        } catch (InvalidProtocolBufferException e) {
            log.error("parse error", e);
            responseObserver.onNext(MsgBuilder.fail("500", "parse error"));
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        responseObserver.onCompleted();
    }
}